import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElTreeSelect,
  ElSpace,
  ElLink,
  ElProgress
} from 'element-plus'
// import { Plus } from '@element-plus/icons-vue'

import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { fnStateEnum } from '~/store/monitor/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import ExportExcel from '~/components/ExportExcel'
import ColorfulBadge from '~/components/ColorfulBadge'

export default defineComponent(function ReportCommunicationEquipment() {
  const store = useStore()
  const router = useRouter()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const equipmentState = useVuexGetters('equipment', [
    'communicationStateOpt',
    'classificationStateOpt',
    'communicationStateEnum'
  ])
  const state = reactive({
    exportVisible: false,
    visible: false,
    deviceId: ''
  })
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '通信时间',
      prop: 'commTime',
      minWidth: 180,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '最新状态',
      prop: 'onlineState',
      minWidth: 160,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true,
      enumValues: equipmentState.communicationStateEnum,
      sortable: true,
      disabled: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.onlineState as unknown as number}
          options={{ success: 1, info: 0, warning: 2 }}
        />
      )
    },
    {
      label: '设备名称',
      prop: 'name',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备编号',
      prop: 'code',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备分类',
      prop: 'categoryName',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '所属工区',
      prop: 'workAreaName',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备品牌',
      prop: 'brandName',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '在线率',
      prop: 'onlineRate',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true,
      render: (_, value) => {
        let num = (value > 1 ? 1 : value) * 100
        num = Number(num.toFixed(1))
        return <ElProgress percentage={num} />
      }
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 160,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => infoOpen(row)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 详情
          </ElLink>
        </ElSpace>
      )
    }
  ]

  onMounted(() => {
    //  设备分类
    store.dispatch('equipment/GetNodeByParentCode')
    //  通信状态
    store.dispatch('equipment/CommunicationStateGet', { code: 'onlineStatus' })
  })
  //  跳转到详情
  const infoOpen = (row: FormValuesType) => {
    router.push({ path: '/monitor/report/communication/info', query: { deviceId: row.deviceId } })
  }
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  // 打开导出弹框
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  return () => (
    <ElCard>
      <ProSaasTable<FormValuesType>
        tableId="monitor_report_communication_index"
        ref={proSaasTableRef}
        columns={columns}
        searchParams={formValues}
        hasSelection
        dispatchType="report/DeviceListPageGet"
        searchFormProps={{
          model: formValues
        }}
        headerTitle={
          <>
            <ElButton type="success" onClick={handleChangeExportModal}>
              <AliIcon type="icon-daochu" />
              &nbsp; 导出
            </ElButton>
          </>
        }
        searchformResponsiveCol={[
          <ElFormItem key="keyWord" prop="keyWord" label="">
            <ElInput
              v-model={formValues.keyWord}
              placeholder="设备名称或设备编号"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="onlineState" prop="onlineState">
            <ElSelect
              v-model={formValues.onlineState}
              clearable
              placeholder="通信状态"
              onChange={clearSearchTable}
            >
              {equipmentState.communicationStateOpt?.value?.map(
                (item: fnStateEnum) =>
                  item?.dictValue !== '未激活' && (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                  )
              )}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="categoryId" prop="categoryId">
            <ElTreeSelect
              v-model={formValues.categoryId}
              placeholder="设备分类"
              data={equipmentState.classificationStateOpt.value}
              checkStrictly // 父级可选
              filterable
              clearable
              props={{
                label: 'title',
                value: 'id'
              }}
            />
          </ElFormItem>
        ]}
      />
      {state.exportVisible && (
        <ExportExcel
          visible={state.exportVisible}
          dispatchType="report/CommunicationExport"
          columns={proSaasTableRef.value?.filterColumns}
          payload={{ params: formValues }}
          onCancel={handleChangeExportModal}
        />
      )}
    </ElCard>
  )
})
